package com.kingtone.rongji.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.kingtone.rongji.MainActivity;
import com.kingtone.rongji.R;
import com.kingtone.rongji.adapter.ProductGirdAdapter;
import com.kingtone.rongji.adapter.ProductListAdapter;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.biz.ProductList;
import com.kingtone.rongji.network.ProductRequest;
import com.kingtone.rongji.tool.AppRestClient;

public class SearchFragment extends BaseFragment  implements OnClickListener {

	private static final String TAG = "SearchFragment";

	public static boolean isGridView = true;

	protected SlidingMenu sm;

	private PullToRefreshListView mPullRefreshListView;
	
	private PullToRefreshGridView mPullRefreshGridView;

	private ProductListAdapter mListAdapter;
	
	private ProductGirdAdapter mGirdAdapter;
	
	private ProductRequest productRequest = new ProductRequest();

	private int listPageIndex = 0;

	private int gridPageIndex = 0;

	public int categoryId = 0;
	
	private String currentOrderBy = "UnitPrice";

	private int currentOrderType = 1;

	public String searchKey = "";
	
	private List<Product> products = new ArrayList<Product>();

	private LayoutInflater mInflater;

	private LinearLayout orderTap;
	
	private PopupWindow popupWindow;
	
	private ImageView grid;
	
	private ImageView list;
	
	private TextView emptyView;
	
	private EditText mEtSearch ;
	
	private View rootView;
	
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onAttach");
		super.onAttach(activity);
		sm = ((MainActivity) activity).getSlidingMenu();
	}

	@Override
	public void onPause() {
		super.onPause();
		searchKey = "";
		categoryId = 0;
		mActivity.setBundle(null);
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onCreateView");
		
		if (rootView == null) {
			
			this.mInflater = inflater;
			
			rootView = inflater.inflate(R.layout.fragment_search, null);
			
			createActionBar(rootView);
			
			createSearchField(rootView);

			createDataList(rootView);
			
			emptyView = (TextView) rootView.findViewById(R.id.results_empty);
		}

		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}	

		this.initData();
		
		return rootView;
	}

	private void createActionBar(View rootView) {
		ImageView menu = (ImageView) rootView.findViewById(R.id.id_img_menu);
		menu.setOnClickListener(this);

		orderTap = (LinearLayout) rootView.findViewById(R.id.id_order);
		orderTap.setOnClickListener(this);

		grid = (ImageView) rootView.findViewById(R.id.id_img_grid);
		grid.setOnClickListener(this);
		
		list = (ImageView) rootView.findViewById(R.id.id_img_list);
		list.setOnClickListener(this);
	}

	public void initData() {
		// TODO Auto-generated method stub
		this.products.clear();
		gridPageIndex = 0;
		listPageIndex = 0;
		Bundle bundle = mActivity.getBundle();
		if(bundle != null)
		{
			searchKey = bundle.getString("KeyWord");
			categoryId = bundle.getInt("catgeoryId");
		}
		productRequest.findByCommon(searchKey, categoryId, 0, currentOrderType,
				currentOrderBy, this.listPageIndex, AppRestClient.PAGE_SIZE,
				this, true);
	}

	private void createDataList(View view) {
		mGirdAdapter = new ProductGirdAdapter(mActivity, products);
		mPullRefreshGridView = (PullToRefreshGridView) view
				.findViewById(R.id.pull_refresh_grid);
		mPullRefreshGridView.setAdapter(mGirdAdapter);
		// 设置监听事件
		mPullRefreshGridView
				.setOnRefreshListener(new OnRefreshListener<GridView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<GridView> refreshView) {
						String label = DateUtils.formatDateTime(mActivity,
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);
						gridPageIndex++;
						doRefresh(refreshView, label, gridPageIndex);
					}
				});
		
		mListAdapter = new ProductListAdapter(mActivity, products);
		mPullRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setAdapter(mListAdapter);

		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(mActivity,
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);
						listPageIndex++;
						doRefresh(refreshView, label, listPageIndex);
					}
				});
	}

	private void doRefresh(PullToRefreshBase refreshView, String label,
			int pageIndex) {
		refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
		productRequest.findByCommon(searchKey, categoryId, 0, currentOrderType,
				currentOrderBy, pageIndex, AppRestClient.PAGE_SIZE,
				SearchFragment.this, false);
	}

	private void createSearchField(View view) {
		mEtSearch = (EditText) view.findViewById(R.id.et_search);
		Button mBtnQuery = (Button) view
				.findViewById(R.id.btn_query);
		mBtnQuery.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchKey = mEtSearch.getText().toString();
				doSearch(searchKey, 0);
			}
		});
	}

	public void doSearch(String key, int id) {
		// TODO Auto-generated method stub
		products.clear();
		this.searchKey = key;
		this.categoryId = id;
		productRequest.findByCommon(searchKey, categoryId, 0, currentOrderType,
						currentOrderBy, 0, AppRestClient.PAGE_SIZE,
						SearchFragment.this, true);
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		int id = view.getId();
		switch (id) {
		case R.id.id_img_grid:
			isGridView = false;
			updateLayout();
			break;
		case R.id.id_img_list:
			isGridView = true;
			updateLayout();
			break;
		case R.id.id_img_menu:
			sm.toggle();
			break;
		case R.id.id_order:
			createOrderPop();
			break;
		default:
			break;
		}
	}

	private void createOrderPop() {
		View contentView = mInflater
				.inflate(R.layout.product_order_popup, null);
		ListView listView = (ListView) contentView
				.findViewById(R.id.order_list);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.mActivity,
				R.layout.search_sort_item, this.getResources()
						.getStringArray(R.array.sort_items));
		listView.setAdapter(adapter);

		if(popupWindow == null)
		{
			popupWindow = new PopupWindow(contentView,
			        WindowManager.LayoutParams.MATCH_PARENT,
			        WindowManager.LayoutParams.WRAP_CONTENT);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.setFocusable(true);
			popupWindow.setOutsideTouchable(true);
		}
		popupWindow.showAsDropDown(orderTap);
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				if (popupWindow != null) {
					popupWindow.dismiss();
				}

				doSort(position);
			}

			private void doSort(int position) {
				switch (position) {
				case 0:
					currentOrderType = 0;
					currentOrderBy = "TotalSoldQty";
					break;
				case 1:
					currentOrderType = 0;
					currentOrderBy = "UnitPrice";
					break;
				case 2:
					currentOrderType = 1;
					currentOrderBy = "UnitPrice";
					break;
				case 3:
					currentOrderType = 0;
					currentOrderBy = "ReviewCount";
					break;
				default:
					break;
				}

				products.clear();
				productRequest.findByCommon(searchKey, categoryId, 0,
						currentOrderType, currentOrderBy, 0,
						AppRestClient.PAGE_SIZE, SearchFragment.this, true);
			}
		});
	}

	private void updateLayout() {
		// TODO Auto-generated method stub
		if (isGridView) {
			grid.setVisibility(View.VISIBLE);
			list.setVisibility(View.GONE);
			mPullRefreshGridView.setVisibility(View.VISIBLE);
			mPullRefreshListView.setVisibility(View.GONE);
			mPullRefreshGridView.invalidate();
		} else {
			list.setVisibility(View.VISIBLE);
			grid.setVisibility(View.GONE);
			mPullRefreshGridView.setVisibility(View.GONE);
			mPullRefreshListView.setVisibility(View.VISIBLE);
			mPullRefreshListView.invalidate();
		}
	}

	@Override
	public void onBussinessSuccess(Object obj) {
		// TODO Auto-generated method stub
		super.onBussinessSuccess(obj);
		if (obj instanceof ProductList) {
			ProductList productList = (ProductList) obj;
			products.addAll(productList.getData());
			mGirdAdapter.notifyDataSetChanged();
			mListAdapter.notifyDataSetChanged();
			if (isGridView) {
				mPullRefreshGridView.onRefreshComplete();
			} else {
				mPullRefreshListView.onRefreshComplete();
			}
			if(products.size() > 0)
			{
				emptyView.setVisibility(View.GONE);
			}
			else
			{
				emptyView.setVisibility(View.VISIBLE);
			}
			this.mEtSearch.setText(this.searchKey);
		}
	}

	public interface OnSearchQueryChangeListener {
		public void onQueryChanged(int catgeoryId, String keyWord, boolean currentTab);
	}
}
